#!/usr/bin/python

import os, tempfile, string

raw_path = "./raw"
work_path = "./work"

jpg_extentions = (".jpg", ".jpeg", ".JPG", ".JPEG")
raw_extentions = (".cr2", ".CR2")

#def ends_with(name, extentions):
#	for ext in extentions:
##		if name[-len(ext):].lower() == ext.lower():
#		if name.endswith(ext):
#			return True
#	return False
#	return name.endswith(extentions)

def is_jpg(name):
	return name.endswith(jpg_extentions)
def is_raw(name):
	return name.endswith(raw_extentions)

def to_raw_path(name):
	print "cr2:(%s)"%name
	assert ends_with(name, jpg_extentions)
	for ext in jpg_extentions:
		if name[-len(ext):].lower() == ext.lower():
			return name[:-len(ext)]+".CR2"

def get_counterpart(name):
	dir, fname = name.rsplit(os.sep, 1)
	fbase, ext = fname.rsplit(".", 1)
	
	yield name	# also return this file...
	if is_jpg(name):
	    for ext in ".cr2 .CR2".split():
		# get corresponding raw file, here: .cr2
		raw_name = fbase + ext
		yield os.path.join(dir, raw_name)
		yield os.path.join(dir, raw_path, raw_name)
	elif is_raw(name):
	    for ext in ".jpg .JPG".split():
		# return corresponding .jpg file
		jpg_name = fbase + ext
		yield os.path.join(dir, jpg_name)

# set up logfile
log = tempfile.NamedTemporaryFile()

# set up stich base dir
base_dir = os.environ["NAUTILUS_SCRIPT_CURRENT_URI"]
base_dir = base_dir[len("file://"):]
#base_dir += os.path.sep+"work"
base_dir = os.path.join(base_dir, work_path)
base_dir = os.path.normpath(base_dir)		# normalize paths like      blub/./blah to blub/blah
if not os.path.exists(base_dir):
	print >> log, "makedirs", base_dir
	os.makedirs(base_dir)

# prepare selection
#print repr(os.environ["NAUTILUS_SCRIPT_SELECTED_FILE_PATHS"])
selected_files = os.environ["NAUTILUS_SCRIPT_SELECTED_FILE_PATHS"].splitlines()
#selected_files = filter(is_jpg, selected_files)
selected_files.sort()

# set up image base directory for stitching as basename (without extention and path) of first file in selection
# select first file, crop directory path, crop extention
img_base, rest = selected_files[0].rsplit(os.sep, 1)[-1].rsplit(".", 1)
print "img_base:", img_base
dest_dir = os.path.join(base_dir, img_base)
print "dest_dir:", dest_dir
if not os.path.exists(dest_dir):
	print >> log, "creating dest_dir:", dest_dir
	os.makedirs(dest_dir)

jpg_cnt, raw_cnt, total_cnt = 0, 0, 0

# process selection
for file_path in selected_files:
	##from shutil import move
	# for each file in selection
	for fn in [file_path]:
		# get corresponding .jpg or .cr2 file
		for counterpart in get_counterpart(fn):		# check for .jpg .cr2 ... counterparts
			if os.path.exists(counterpart):
				print >> log, "moving:", counterpart.split(os.sep)[-1] #, "to", dest_dir
				cmd = "mv %s %s"%(counterpart, dest_dir)
				#print >> log, cmd
				os.system(cmd)
				##move(counterpart, dest_dir)
				# do statistics
				total_cnt += 1
				if is_jpg(counterpart): jpg_cnt += 1
				if is_raw(counterpart): raw_cnt += 1
			else:
				#print fn, "does not exist"
				pass
print >> log, "move: %ix.jpg + %ix.cr2 = %i total"%(jpg_cnt, raw_cnt, total_cnt)

log.flush()
os.system("zenity --text-info --filename %s"%(log.name))

